#include <iostream>
#include "../Api Headers/DataTree.hpp"
#include "RequestParser.hpp"

RequestParser::RequestParser()
{

}

RequestParser::~RequestParser()
{

}

void		RequestParser::ParseRequest(const std::string &Request, zia::api::DataTree &Tree, std::string &Body)
{
  if (CheckRequestIntegrity(Request))
    {
		//	doStepActions(zia::api::HttpStepID::STEP_PARSER);
      GetHeader(Request, Body);
      ParseFirstLine(Tree);
      ParseHeader(GetNextLine(), Tree);
     // Tree.print(std::cout);
    }
  else
    std::cerr << "Bad Request, dropped" << std::endl;
}

bool		RequestParser::CheckRequestIntegrity(const std::string &Request)
{
  std::string	tmp;
  std::string	fl;

  tmp = Request;
  if (int(tmp.find("\r\n")) != -1)
    {
      fl = tmp.substr(0, tmp.find("\r\n"));
      tmp.erase(0, tmp.find("\r\n") + 2);
      if (int(fl.find(' ')) != -1 && int(fl.rfind(' ')) != -1)
	{
	  while (!tmp.empty() && !tmp.compare("\r\n"))
	    {
	      if (int(tmp.find(": ")) != -1 && int(tmp.find("\r\n")) != -1)
		tmp = tmp.erase(0, tmp.find("\r\n") + 2);
	      std::cout << "HERE|" << tmp << "|" << std::endl;
	    }
	  if (tmp.empty() || tmp.compare("\r\n"))
	    return (true);
	}
    }
  return (false);
}

void		RequestParser::GetHeader(const std::string &Request, std::string &Body)
{
  this->_request = Request.substr(0, Request.find("\r\n\r") + 2);
  Body = Request.substr(Request.find("\r\n\r") + 3, Request.size() - (Request.find("\r\n\r") + 3));
//  std::cout << this->_request << "\n------------- Parsing -------------\n";
}

void		RequestParser::ParseFirstLine(zia::api::DataTree &Tree)
{
  std::string	tmp = this->_request.substr(0, this->_request.find("\r\n"));

  this->_request.erase(0, this->_request.find("\r\n") + 2);
//   tmp.erase(0, tmp.find(':') + 2);
  Tree["Method"] = tmp.substr(0, tmp.find(' '));
  Tree["URL"] = tmp.substr(tmp.find(' ') + 1, tmp.rfind(' ') - (tmp.find(' ') + 1));
  Tree["Version"] = tmp.substr(tmp.rfind(' ') + 1, tmp.find("\r\n"));
}

std::string	RequestParser::GetNextLine()
{
  std::string	to_parse;
  to_parse = this->_request.substr(0, this->_request.find("\r\n"));
  this->_request.erase(0, this->_request.find("\r\n") + 2);
  return (to_parse);
}

void		RequestParser::ParseHeader(std::string to_parse, zia::api::DataTree &Tree)
{
  if (to_parse.empty() || to_parse == "\r\n")
    return ;
  else
    {
      Tree[to_parse.substr(0, to_parse.find(": "))] = to_parse.substr(to_parse.find(": ") + 2, to_parse.find("\r\n") - to_parse.find(": "));
      ParseHeader(GetNextLine(), Tree);
    }
  return ;
}
